package com.example.pagingdemo.paging.githubuser;

import android.app.Application;
import android.os.AsyncTask;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.paging.PagedList;

import com.example.pagingdemo.api.Api;
import com.example.pagingdemo.api.RetrofitClient;
import com.example.pagingdemo.db.UserDatabase;
import com.example.pagingdemo.model.GithubUser;
import com.example.pagingdemo.paging.PageConfig;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author: tuyrt7 on 2020/9/9.
 */
public class GithubUserBoundaryCallback extends PagedList.BoundaryCallback<GithubUser> {

    private static final String TAG = "BoundaryCallback";
    private Application mApplication;

    public GithubUserBoundaryCallback(Application application) {
        mApplication = application;
    }

    @Override
    public void onZeroItemsLoaded() {
        super.onZeroItemsLoaded();
        Log.d(TAG, "onZeroItemsLoaded: =========没有数据=====");
        getTopData();
    }

    @Override
    public void onItemAtFrontLoaded(@NonNull GithubUser itemAtFront) {
        super.onItemAtFrontLoaded(itemAtFront);
        //新提交的PagedList第一条数据被加载到列表时,回调
    }

    @Override
    public void onItemAtEndLoaded(@NonNull GithubUser itemAtEnd) {
        super.onItemAtEndLoaded(itemAtEnd);
        Log.d(TAG, "onItemAtEndLoaded: =========滑动到底部=====");
        getTopAfterData(itemAtEnd);
    }

    /**
     * 加载第一页数据
     */
    private void getTopData() {
        getData(0);
    }

    /**
     * 加载下一页数据
     */
    private void getTopAfterData(GithubUser user) {
        getData(user.id);
    }

    private void getData(int since) {
        RetrofitClient.get().buildApi(Api.BASE_URL3)
                .getGithubUsers(since, PageConfig.PER_PAGE_SIZE)
                .enqueue(new Callback<List<GithubUser>>() {
                    @Override
                    public void onResponse(Call<List<GithubUser>> call, Response<List<GithubUser>> response) {
                        if (response.body() != null) {
                            insertGithubUsers(response.body());
                            if (since > 0) {
                                Log.d("aaaa", "下一页获得数据: " + response.body());
                            } else {
                                Log.d("aaaa", "获得数据: " + response.body());
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<List<GithubUser>> call, Throwable t) {

                    }
                });
    }

    private void insertGithubUsers(List<GithubUser> githubUsers) {
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                UserDatabase.get(mApplication).githubUserDao().insertUsers(githubUsers);
            }
        });
    }
}
